<template>
  <div style="background-color: #f6f8f9; height: 100%">
    <template v-if="!form">加载中...</template>
    <el-row style="height: 98%" :gutter="20" v-else>
      <el-col :span="12" style="height: 100%; overflow: auto">
        <div class="section">
          {{ form.WFM_DepartmentId }}
          <vanPicker :columns="departments.map((x) => {
            return { name: x.DPM_Name, id: x.DPM_ID }
          })
            " v-model="form.WFM_DepartmentId" title="部门" />
          <el-form label-width="140px" label-position="left">
            <el-form-item label="部门" style="margin: 10px" v-if="!formId" required>
              <el-select v-model="form.WFM_DepartmentId" placeholder="请选择所属部门">
                <el-option v-for="dpm in departments" :key="dpm.DPM_ID" :label="dpm.DPM_Name"
                  :value="dpm.DPM_ID"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="搜寻码" style="margin: 10px" v-if="form.WFM_FormDataCode">
              <el-link type="primary">{{ form.WFM_FormDataCode }}</el-link>
            </el-form-item>
          </el-form>
          <div v-for="(field, index) in formFields" :key="index">
            <form-field :form="form" :formField="field" :isBusiness="false"
              @change="formFieldChange(field)"></form-field>
          </div>
        </div>
      </el-col>
      <el-col :span="10" style="height: 100%">
        <div class="section" style="position: relative">
          <div style="height: calc(100% - 80px); overflow-y: auto">
            <formstep :form="form"></formstep>
          </div>

          <div style="
              position: absolute;
              height: 60px;
              width: 90%;
              border-top: #f3f3f3 2px solid;
              bottom: 0px;
              display: flex;
              align-items: center;
              justify-content: start;
              background-color: white;
            ">
            <el-button type="primary" @click="showPass" v-if="form.Auth.PassAble">
              通过
            </el-button>
            <el-button type="warning" @click="returnVis = true" v-if="form.Auth.ReturnAble">
              回退
            </el-button>
            <el-button type="warning" @click="rejectVis = true" v-if="form.Auth.RejectAble">
              拒绝
            </el-button>
            <el-button type="warning" @click="cancelVis = true" v-if="form.Auth.CancelAble">
              撤销
            </el-button>
            <el-button type="primary" @click="showDeliver" v-if="form.Auth.DeliverAble">
              转交
            </el-button>
            <el-button type="primary" @click="saveVis = true" v-if="form.Auth.SaveAble">
              保存
            </el-button>
            <el-button type="primary" @click="formSubmit" v-if="form.Auth.SubmitAble">
              提交
            </el-button>
            <el-button type="primary" @click="commentVis = true" v-if="form.Auth.CommentAble">
              评论
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-dialog title="审核通过" :visible.sync="passVis" width="30%">
      <div v-for="(field, index) in actionFields" :key="index">
        <form-field v-if="field.show" :form="form" :formField="field" :isBusiness="false"></form-field>
      </div>
      <el-form>
        <el-form-item v-if="form && form.CurStep">
          <el-checkbox v-for="item in form.CurStep.Actions" :key="item.FSA_ID" v-model="item.FSA_OperatorChoose"
            :disabled="item.BFA_Type == 10">
            {{ item.BFA_Name }}
          </el-checkbox>
        </el-form-item>
        <el-form-item v-if="form && form.CurStep && form.CurStep.FRS_PassType == 2">
          <canvas style="background-color: #eeeeee" ref="myCanvas" />
          <el-button @click="saveSign" type="text" icon="el-icon-circle-check" title="确认" :disabled="signDisable">
            保存签名
          </el-button>
          <el-button @click="clean" type="text" icon="el-icon-delete" title="确认">
            清空
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-input v-model="comment" type="textarea" :rows="4" placeholder="请输入回复"></el-input>
        </el-form-item>
        <el-form-item>
          <div v-for="(file, index) in files" :key="file.FL_ID" style="margin: 2px">
            文件{{ index + 1 }}: {{ file.FL_Name }}

            <el-button type="text" icon="el-icon-delete" @click="removeFile(index)"></el-button>
          </div>
          <el-upload :action="fileUploadUrl" :on-error="uploadErr" multiple :show-file-list="false" :headers="myHeaders"
            :on-success="uploadFinish">
            <el-button type="default" class="upload-button" icon="el-icon-plus"></el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="formPass" type="primary" icon="el-icon-circle-check" title="确认">
            确认
          </el-button>
          <el-button @click="passVis = false" title="取消">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="保存" :visible.sync="saveVis" width="30%">
      <el-form>
        <el-form-item>
          <el-input v-model="comment" type="textarea" :rows="4" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item>
          <div v-for="(file, index) in files" :key="file.FL_ID" style="margin: 2px">
            文件{{ index + 1 }}: {{ file.FL_Name }}

            <el-button type="text" icon="el-icon-delete" @click="removeFile(index)"></el-button>
          </div>
          <el-upload :action="fileUploadUrl" :on-error="uploadErr" multiple :show-file-list="false" :headers="myHeaders"
            :on-success="uploadFinish">
            <el-button type="default" class="upload-button" icon="el-icon-plus"></el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="formSave" type="primary" icon="el-icon-circle-check" title="确认">
            确认
          </el-button>
          <el-button @click="saveVis = false" title="取消">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="评论" :visible.sync="commentVis" width="30%">
      <el-form>
        <el-form-item>
          <el-input v-model="comment" type="textarea" :rows="4" placeholder="请输入评论内容"></el-input>
        </el-form-item>
        <el-form-item>
          <div v-for="(file, index) in files" :key="file.FL_ID" style="margin: 2px">
            文件{{ index + 1 }}: {{ file.FL_Name }}

            <el-button type="text" icon="el-icon-delete" @click="removeFile(index)"></el-button>
          </div>
          <el-upload :action="fileUploadUrl" :on-error="uploadErr" multiple :show-file-list="false" :headers="myHeaders"
            :on-success="uploadFinish">
            <el-button type="default" class="upload-button" icon="el-icon-plus"></el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="formComment" type="primary" icon="el-icon-circle-check" title="确认">
            确认
          </el-button>
          <el-button @click="commentVis = false" title="取消">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="回退" :visible.sync="returnVis" width="30%">
      <el-form>
        <el-form-item label="回退类型">
          <el-select v-model="returnType">
            <el-option v-for="type in returnTypes" :key="type.EnumValue" :label="type.Description"
              :value="type.EnumValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="节点选择" v-if="returnType == 30">
          <!-- 回退到指定节点 -->
          <el-select v-model="appointStep" value-key="FRS_ID">
            <el-option v-for="step in preSteps" :key="step.FRS_ID" :label="step.FRS_Name" :value="step"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="comment" type="textarea" :rows="4" placeholder="请输入回复"></el-input>
        </el-form-item>
        <el-form-item>
          <div v-for="(file, index) in files" :key="file.FL_ID" style="margin: 2px">
            文件{{ index + 1 }}: {{ file.FL_Name }}

            <el-button type="text" icon="el-icon-delete" @click="removeFile(index)"></el-button>
          </div>
          <el-upload :action="fileUploadUrl" :on-error="uploadErr" multiple :show-file-list="false" :headers="myHeaders"
            :on-success="uploadFinish">
            <el-button type="default" class="upload-button" icon="el-icon-plus"></el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="formReturn" type="primary" icon="el-icon-circle-check" title="确认">
            确认
          </el-button>
          <el-button @click="returnVis = false" title="取消">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="拒绝" :visible.sync="rejectVis" width="30%">
      <el-form>
        <el-form-item>
          <el-input v-model="comment" type="textarea" :rows="4" placeholder="请输入回复"></el-input>
        </el-form-item>
        <el-form-item>
          <div v-for="(file, index) in files" :key="file.FL_ID" style="margin: 2px">
            文件{{ index + 1 }}: {{ file.FL_Name }}

            <el-button type="text" icon="el-icon-delete" @click="removeFile(index)"></el-button>
          </div>
          <el-upload :action="fileUploadUrl" :on-error="uploadErr" multiple :show-file-list="false" :headers="myHeaders"
            :on-success="uploadFinish">
            <el-button type="default" class="upload-button" icon="el-icon-plus"></el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="formReject" type="primary" icon="el-icon-circle-check" title="确认">
            确认
          </el-button>
          <el-button @click="rejectVis = false" title="取消">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="撤销" :visible.sync="cancelVis" width="30%">
      <el-form>
        <el-form-item>
          <el-input v-model="comment" type="textarea" :rows="4" placeholder="请输入回复"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="formCancel" type="primary" icon="el-icon-circle-check" title="确认">
            确认
          </el-button>
          <el-button @click="cancelVis = false" title="取消">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="转交" :visible.sync="deliverVis" width="30%">
      <el-form>
        <el-form-item label="转交人">
          <el-select filterable v-model="toEmp" placeholder="请选择转交人" value-key="ECV_TargetID">
            <el-option v-for="emp in emps" :key="emp.ECV_TargetID" :label="emp.USR_Name" :value="emp"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="comment" type="textarea" :rows="4" placeholder="请输入回复"></el-input>
        </el-form-item>
        <el-form-item>
          <div v-for="(file, index) in files" :key="file.FL_ID" style="margin: 2px">
            文件{{ index + 1 }}: {{ file.FL_Name }}

            <el-button type="text" icon="el-icon-delete" @click="removeFile(index)"></el-button>
          </div>
          <el-upload :action="fileUploadUrl" :on-error="uploadErr" multiple :show-file-list="false" :headers="myHeaders"
            :on-success="uploadFinish">
            <el-button type="default" class="upload-button" icon="el-icon-plus"></el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="formDeliver" type="primary" icon="el-icon-circle-check" title="确认">
            确认
          </el-button>
          <el-button @click="deliverVis = false" title="取消">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  baseURL,
  fileRoot,
  fileUploadRoot,
  tokenName,
  empIdName,
} from '@/config'
import formField from '@/views/phone/form/formField.vue'
import {
  formSave,
  formPass,
  formReturn,
  formCancel,
  formReject,
  formDeliver,
  formComment,
  getReturnTypes,
  getFlow,
  getForm,
  startForm,
  getFormSteps,
  getDepartments,
  getEmployees,
} from '@/api/flowCenter/form/formProcess'
import formstep from '@/views/web/formManage/componenets/formstep.vue'
import vanPicker from '@/views/phone/components/vanPicker.vue'
import axios from 'axios'
export default {
  components: { formField, formstep, vanPicker },
  data: function () {
    return {
      canvas: null,
      board: null,
      mousePress: false,

      emps: null,
      toEmp: null,
      returnTypes: [],
      flowId: null,
      formId: null,
      msgId: null,
      form: null,
      comment: null,
      signFile: null,
      files: [],
      returnType: null,
      appointStep: null,
      passVis: false,
      saveVis: false,
      returnVis: false,
      rejectVis: false,
      cancelVis: false,
      deliverVis: false,
      commentVis: false,
      signDisable: false,
      departments: null,
      fileURL: baseURL + fileRoot,
      fileUploadUrl: baseURL + fileUploadRoot,
      myHeaders: {},
    }
  },
  computed: {
    preSteps() {
      //当前节点之前的审核节点
      return this.form
        ? this.form.FormSteps.filter(
          (x) => x.FRS_Index < this.form.CurStep.FRS_Index && x.FRS_Type == 3
        )
        : []
    },
    formFields() {
      return this.form
        ? this.form.FieldValues.filter((x) => !x.BFF_InAction)
        : []
    },
    actionFields() {
      let fields = this.form
        ? this.form.FieldValues.filter((x) => x.BFF_InAction) // 筛选具有 BFF_InAction 属性为 true 的字段
        : [] // 如果 this.form 不存在，则返回空数组
      if (this.form && this.form.CurStep && this.form.CurStep.Actions) {
        let curActions = this.form.CurStep.Actions.filter(
          (y) => y.FSA_OperatorChoose // 筛选具有 FSA_OperatorChoose 属性为 true 的操作步骤
        )
        fields.forEach((field) => {
          field.show = false // 初始化字段的 show 属性为 false
          field.Actions.forEach((x) => {
            if (curActions.find((y) => y.BFA_Guid == x.BFFA_ActionGuid)) {
              field.show = true // 如果存在匹配的操作步骤，则将字段的 show 属性设置为 true
            }
          })
        })
      }
      return fields // 返回处理后的字段数组
    },
  },
  methods: {
    showPass() {
      this.passVis = true
      if (this.form.CurStep.FRS_PassType == 2) {
        this.$nextTick(() => {
          this.initCanvas()
        })
      }
    },
    initCanvas() {
      if (this.canvas) {
        return
      }
      this.canvas = this.$refs.myCanvas
      this.canvas.height = 200
      this.canvas.width = 500

      this.board = this.canvas.getContext('2d')
      this.board.lineWidth = 1 //设置画笔粗细
      this.board.strokeStyle = '#000'
      this.board.lineJoin = 'round' //设置画笔轨迹基于圆点拼接

      this.canvas.onmousedown = this.beginDraw
      this.canvas.onmousemove = this.drawing
      this.canvas.onmouseup = this.endDraw
      this.canvas.addEventListener('touchstart', this.beginDraw, false)
      this.canvas.addEventListener('touchmove', this.drawing, false)
      this.canvas.addEventListener('touchend', this.endDraw, false)
    },

    beginDraw() {
      this.mousePress = true
    },
    endDraw(event) {
      this.mousePress = false
      event.preventDefault()
      this.last = null
    },
    drawing(event) {
      event.preventDefault()
      if (!this.mousePress) return
      var xy = this.getPos(event)
      if (this.last != null) {
        this.board.beginPath()
        this.board.moveTo(this.last.x, this.last.y)
        this.board.lineTo(xy.x, xy.y)
        this.board.stroke()
      }
      this.last = xy
    },
    getPos(event) {
      var isTouch = event.type.indexOf('touch') >= 0 ? true : false
      var x = isTouch
        ? event.touches[0].pageX
        : event.offsetX + event.target.offsetLeft
      var y = isTouch
        ? event.touches[0].pageY
        : event.offsetY + event.target.offsetTop
      return { x: x, y: y }
    },
    clean() {
      this.board.clearRect(0, 0, this.canvas.width, this.canvas.height)
      this.signFile = null
      this.signDisable = false
    },
    saveSign() {
      this.canvas.toBlob((result) => {
        let form = new FormData()
        form.append('file', result)
        let config = {
          baseURL,
          headers: { 'Content-Type': 'multipart/form-data' },
        }
        config.headers[tokenName] = this.$store.getters['user/accessToken']
        config.headers[empIdName] = this.$store.getters['user/curEmp'].EMP_ID
        axios
          .post(this.fileUploadUrl, form, config)
          .then(({ data }) => {
            this.signFile = data.data
            this.signDisable = true
          })
          .catch((err) => {
            this.$message.warning('签名上传失败，请重试!')
          })
      })
    },
    showDeliver() {
      if (this.emps) {
        this.deliverVis = true
        return
      }
      getEmployees().then(({ data }) => {
        this.emps = data
        this.deliverVis = true
      })
    },
    removeFile(index) {
      this.files.splice(index, 1)
    },
    uploadErr: function (err) {
      alert(JSON.stringify(err))
    },
    uploadFinish(data, file) {
      if (data.success) {
        this.files.push(data.data)
      } else {
        alert(data.errormsg)
      }
    },
    formFieldChange(field) {
      if (this.$route.query.flowId) {
        if (field.IsCondition) {
          getFormSteps(this.form).then(({ data }) => {
            this.form.FormSteps = data
          })
        }
      }
    },
    getReturnTypes() {
      getReturnTypes().then(({ data }) => {
        this.returnTypes = data
      })
    },
    formSubmit() {
      startForm(this.form).then(({ data }) => {
        this.formId = data
        this.getForm()
      })
    },
    formDeliver() {
      formDeliver({
        Comment: this.comment,
        Form: this.form,
        Files: this.files,
        ToEmp: this.toEmp,
      }).then((r) => {
        this.getForm()
        this.$message('操作成功')
        this.comment = null
        this.files = []
        this.deliverVis = false
      })
    },
    formPass() {
      if (this.form.CurStep.FRS_PassType == 2 && !this.signFile) {
        this.$message('请先签名并保存')
        return
      }
      formPass({
        SignFileID: this.signFile ? this.signFile.FL_ID : null,
        Comment: this.comment,
        Form: this.form,
        Files: this.files,
      }).then((r) => {
        this.getForm()
        this.$message('操作成功')
        this.comment = null
        this.files = []
        this.passVis = false
      })
    },
    formSave() {
      formSave({
        Comment: this.comment,
        Form: this.form,
        Files: this.files,
      }).then((r) => {
        this.getForm()
        this.$message('保存成功')
        this.comment = null
        this.files = []
        this.saveVis = false
      })
    },
    formComment() {
      formComment({
        Comment: this.comment,
        Form: this.form,
        Files: this.files,
      }).then((r) => {
        this.getForm()
        this.$message('评论成功')
        this.comment = null
        this.files = []
        this.commentVis = false
      })
    },
    formReturn() {
      if (!this.returnType) {
        this.$message('请选择回退类型')
        return
      }
      formReturn({
        Type: this.returnType,
        Comment: this.comment,
        Form: this.form,
        AppointStep: this.appointStep,
        Files: this.files,
      }).then((r) => {
        this.getForm()
        this.$message('操作成功')
        this.returnType = null
        this.comment = null
        this.appointStep = null
        this.files = []
        this.returnVis = false
      })
    },
    formCancel() {
      formCancel({
        Comment: this.comment,
        Form: this.form,
      }).then((r) => {
        this.getForm()
        this.$message('操作成功')
        this.cancelVis = false
      })
    },
    formReject() {
      formReject({
        Comment: this.comment,
        Form: this.form,
        Files: this.files,
      }).then((r) => {
        this.getForm()
        this.$message('操作成功')
        this.comment = null
        this.files = []
        this.rejectVis = false
      })
    },
    getFlow() {
      getFlow(this.flowId).then(({ data }) => {
        this.form = data
        this.form.WFM_DepartmentId = null
        getFormSteps(this.form).then(({ data }) => {
          this.form.FormSteps = data
        })
      })
    },
    getForm() {
      getForm(this.formId, this.msgId).then(({ data }) => {
        this.form = data
        if (this.form.WFM_DepartmentId == 0) {
          this.form.WFM_DepartmentId = null
        }
      })
    },
    getDepartments() {
      getDepartments().then(({ data }) => {
        this.departments = data
      })
    },
  },
  mounted() {
    if (!this.$route.query.formId && !this.$route.query.flowId) {
      return
    }
    if (this.$route.query.formId) {
      this.formId = this.$route.query.formId
      if (this.$route.query.msgId) {
        this.msgId = this.$route.query.msgId
      }
      this.getReturnTypes()
      this.getForm()
    } else {
      this.flowId = this.$route.query.flowId
      this.getFlow()
    }
    this.getDepartments()
    this.myHeaders[tokenName] = this.$store.getters['user/accessToken']
    this.myHeaders[empIdName] = this.$store.getters['user/curEmp'].EMP_ID
  },
}
</script>
<style scoped>
.section {
  background-color: white;
  height: 100%;
  padding: 30px 20px;
  border-radius: 10px;
  box-sizing: border-box;
  overflow: auto;
  width: 100%;
}
</style>